export class FormatHandler {
  constructor(editorCore) {
    this.editor = editorCore
    this.commands = new Map()
    this.registerDefaultCommands()
  }

  registerDefaultCommands() {
    this.registerCommand('bold', {
      execute: () => this.toggleFormat('bold'),
      queryState: () => this.queryFormatState('bold')
    })

    this.registerCommand('italic', {
      execute: () => this.toggleFormat('italic'),
      queryState: () => this.queryFormatState('italic')
    })

    this.registerCommand('underline', {
      execute: () => this.toggleFormat('underline'),
      queryState: () => this.queryFormatState('underline')
    })

    this.registerCommand('foreColor', {
      execute: (color) => this.applyFormat('foreColor', color),
      queryState: () => this.queryFormatState('foreColor')
    })

    this.registerCommand('hiliteColor', {
      execute: (color) => this.applyFormat('hiliteColor', color),
      queryState: () => this.queryFormatState('hiliteColor')
    })
  }

  registerCommand(name, command) {
    this.commands.set(name, command)
  }

  executeCommand(name, ...args) {
    const command = this.commands.get(name)
    if (command) {
      const result = command.execute(...args)
      this.editor.historyManager.recordState(this.editor.getContent())
      return result
    }
    return false
  }

  queryCommandState(name) {
    const command = this.commands.get(name)
    return command ? command.queryState() : false
  }

  toggleFormat(format, value = null) {
    if (this.editor.selectionHandler.isSelectionValid()) {
      document.execCommand(format, false, value || null)
      return true
    }
    return false
  }

  applyFormat(format, value) {
    if (this.editor.selectionHandler.isSelectionValid()) {
      document.execCommand(format, false, value)
      return true
    }
    return false
  }

  queryFormatState(format) {
    return document.queryCommandState(format)
  }

  getFormatValue(format) {
    return document.queryCommandValue(format)
  }
}
